const handleGenerate = async () => {
  try {
    loading.value = true
    console.log('提交图片生成请求:', {
      subject: form.subject,
      grade: form.grade,
      topic: form.topic,
      description: form.description
    })
    
    const response = await generateImage({
      subject: form.subject,
      grade: form.grade,
      topic: form.topic,
      description: form.description
    })
    
    console.log('图片生成响应:', response)
    
    if (response && response.data) {
      const imageUrl = response.data
      console.log('获取到的图片URL:', imageUrl)
      
      // 检查图片URL是否有效
      if (!imageUrl || typeof imageUrl !== 'string') {
        throw new Error('无效的图片URL格式')
      }
      
      // 创建新的图片资源对象
      const newImage = {
        id: Date.now(), // 临时ID
        title: form.topic,
        description: form.description,
        subject: form.subject,
        grade: form.grade,
        url: imageUrl,
        createdTime: new Date().toISOString()
      }
      
      // 将新图片添加到图片列表
      images.value.unshift(newImage)
      
      ElMessage.success('图片生成成功')
      
      // 刷新图片列表
      await fetchImages()
    } else {
      throw new Error('未获取到图片URL')
    }
  } catch (error) {
    console.error('生成图片失败:', error)
    ElMessage.error('生成图片失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 图片展示组件
const ImageCard = {
  props: {
    image: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const { ref, computed } = Vue
    
    const imageUrl = computed(() => {
      // 确保URL是完整的
      if (props.image.url && !props.image.url.startsWith('http')) {
        return `http://${props.image.url}`
      }
      return props.image.url
    })
    
    const imageError = ref(false)
    
    const handleImageError = () => {
      console.error('图片加载失败:', props.image.url)
      imageError.value = true
    }
    
    return {
      imageUrl,
      imageError,
      handleImageError
    }
  },
  template: `
    <el-card class="image-card">
      <template v-if="!imageError">
        <img :src="imageUrl" :alt="image.title" @error="handleImageError" />
      </template>
      <template v-else>
        <div class="image-error">
          <el-icon><picture-failed /></el-icon>
          <p>图片加载失败</p>
        </div>
      </template>
      <div class="image-info">
        <h3>{{ image.title }}</h3>
        <p>{{ image.description }}</p>
        <p>学科: {{ image.subject }}</p>
        <p>年级: {{ image.grade }}</p>
        <p>生成时间: {{ new Date(image.createdTime).toLocaleString() }}</p>
      </div>
    </el-card>
  `
} 